package com.sds.batch;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.sds.batch.util.BatchUtil;

@Component
public class JobRunner {
	private final static String[] locations = new String[] { "classpath:spring/context-datasource.xml",
			"classpath:spring/context-batch.xml",
			"classpath:**/*_Job.xml" };
	private final static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
			locations, false);
	
	static {
		context.refresh();
	}
	
	private Logger logger = LoggerFactory.getLogger(JobRunner.class);
	
	public static void main(String[] args) throws Exception {
		new JobRunner().launchJob("job1",new JobParameters());
	}
	
	public void launchJob(String jobName, JobParameters jobParameters) throws Exception {
		JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
//		Job job = (Job) context.getBean(jobName);
		JobRegistry jobRegistry = (JobRegistry) context.getBean("jobRegistry");
		Job job = jobRegistry.getJob(jobName);
		
		
		JobExecution jobExecution = launcher.run(job, BatchUtil.getUniqueParameters(jobParameters));
		logger.info("#################################################");
		logger.info("Job Name         : " + jobName);
		logger.info("Job ID           : " + jobExecution.getJobId());
		logger.info("Job Parameters   : " + jobExecution.getJobInstance().getJobParameters());
		logger.info("Create Time      : " + jobExecution.getCreateTime());
		logger.info("Start Time       : " + jobExecution.getStartTime());
		logger.info("End Time         : " + jobExecution.getEndTime());
		logger.info("Exit Status      : " + jobExecution.getExitStatus().getExitCode());
		Collection<StepExecution> stepExecutions = jobExecution.getStepExecutions();
		for( StepExecution stepExecution : stepExecutions ) {
			logger.info("=================================================");
			logger.info("Step Name        : " + stepExecution.getStepName());
			logger.info("Step ID          : " + stepExecution.getId());
			logger.info("Job Parameters   : " + stepExecution.getJobParameters());
			logger.info("Step Read Count  : " + stepExecution.getReadCount());
			logger.info("Step Write Count : " + stepExecution.getWriteCount());
			logger.info("Start Time       : " + stepExecution.getStartTime());
			logger.info("End Time         : " + stepExecution.getEndTime());
			logger.info("Exit Status      : " + stepExecution.getExitStatus().getExitCode());
		}
		logger.info("#################################################");
	}
}
